<template>
  <view v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <view class="modal-container" @click.stop>
      <view class="modal-header">
        <text class="modal-title">历史自检失败详情</text>
        <text class="close-btn" @click="$emit('close')">×</text>
      </view>
      
      <view class="modal-content">
        <view class="content-layout">
          <!-- 左侧规则列表 -->
          <view class="rules-panel">
            <view class="panel-header">
              <text class="panel-title">验证规则列表</text>
            </view>
            
            <view class="rules-list">
              <view 
                v-for="(rule, index) in rulesData" 
                :key="index"
                class="rule-item"
                :class="{ 
                  'rule-failed': !rule.result, 
                  'rule-passed': rule.result,
                  'rule-selected': selectedRuleIndex === index
                }"
                @click="selectRule(index)"
              >
                <view class="rule-header">
                  <view class="rule-status">
                    <text class="status-icon" :class="rule.result ? 'success' : 'error'">
                      {{ rule.result ? '✓' : '✗' }}
                    </text>
                    <text class="rule-name">{{ getDisplayRuleName(rule) }}</text>
                  </view>
                </view>
                <!-- 显示项目和站点信息 -->
                <!-- <view v-if="rule.project_id || rule.site_id" class="project-site-info">
                  <text class="info-text" v-if="rule.project_id">项目: {{ rule.project_name || rule.project_id }}</text>
                  <text class="info-text" v-if="rule.site_id">站点: {{ rule.site_name || rule.site_id }}</text>
                </view> -->
              </view>
            </view>
          </view>
          
          <!-- 右侧详细信息 -->
          <view class="details-panel">
            <view v-if="selectedRule" class="rule-details">
              <view class="detail-header">
                <text class="detail-title">{{ selectedRule.rule_name }}</text>
                <view class="detail-status-badge" :class="selectedRule.result ? 'success' : 'error'">
                  {{ selectedRule.result ? '验证通过' : '验证失败' }}
                </view>
              </view>
              
              <!-- 项目和站点信息 -->
              <view v-if="selectedRule.project_id || selectedRule.site_id" class="project-site-details">
                <view class="info-section">
                  <text class="info-label">项目信息:</text>
                  <view class="info-content">
                    <text v-if="selectedRule.project_id">ID: {{ selectedRule.project_id }}</text>
                    <text v-if="selectedRule.project_name">名称: {{ selectedRule.project_name }}</text>
                  </view>
                </view>
                <view class="info-section">
                  <text class="info-label">站点信息:</text>
                  <view class="info-content">
                    <text v-if="selectedRule.site_id">ID: {{ selectedRule.site_id }}</text>
                    <text v-if="selectedRule.site_name">名称: {{ selectedRule.site_name }}</text>
                  </view>
                </view>
              </view>
              
              <!-- 规则描述 -->
              <view v-if="selectedRule.description" class="rule-description">
                <text class="description-label">规则说明：</text>
                <text class="description-text">{{ selectedRule.description }}</text>
              </view>
              
              <!-- 验证结果说明 -->
              <!-- <view class="result-summary">
                <text class="summary-label">验证结果：</text>
                <text class="summary-text" :class="selectedRule.result ? 'success-text' : 'error-text'">
                  {{ getResultSummary(selectedRule) }}
                </text>
              </view> -->
              
              <!-- 规则详细说明 -->
              <view class="rule-reason-section">
                <text class="section-title">验证说明：</text>
                <view class="reason-content" :class="selectedRule.result ? 'success-content' : 'error-content'">
                  <text class="reason-text">{{ selectedRule.reason || '无详细说明' }}</text>
                </view>
              </view>
              
              <!-- 信任按钮 -->
              <view v-if="!selectedRule.result" class="trust-section">
                <button class="trust-btn" @click="handleTrustRule" :loading="trustLoading">
                  {{ trustLoading ? '处理中...' : '自检错误？点此反馈' }}
                </button>
              </view>
            </view>
            
            <!-- 未选择规则时的提示 -->
            <view v-else class="no-selection">
              <text class="no-selection-text">请从左侧选择一个规则查看详细信息</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="modal-footer">
        <button class="export-btn" @click="exportReport">导出报告</button>
        <button class="close-footer-btn" @click="$emit('close')">关闭</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  checkData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

const selectedRuleIndex = ref(-1)
const expandedRules = ref([])
const trustLoading = ref(false)

const rulesData = computed(() => {
  if (!props.checkData || !props.checkData.detail) {
    return []
  }
  
  // 将检查数据转换为规则数组
  const rules = []
  const detail = props.checkData.detail
  
  // 处理新的数据结构：{ "规则名：xxx": [[...], [...], ...] }
  Object.keys(detail).forEach(key => {
    const items = detail[key]
    if (Array.isArray(items)) {
      // 遍历每个规则项
      items.forEach((item, itemIndex) => {
        if (Array.isArray(item) && item.length >= 2) {
          // 解析数组格式：[结果字符串, 说明文字, 项目ID, 项目名称, 站点ID, 站点名称]
          const resultStr = item[0]
          const reason = item[1]
          const project_id = item.length > 2 ? item[2] : null
          const project_name = item.length > 3 ? item[3] : null
          const site_id = item.length > 4 ? item[4] : null
          const site_name = item.length > 5 ? item[5] : null
          const result = resultStr === 'true' || resultStr === true
          
          // 为每个规则项创建单独的规则对象
          rules.push({
            rule_name: key.replace('规则名：', ''), // 移除"规则名："前缀
            result: result,
            description: '',
            reason: reason,
            project_id: project_id,
            project_name: project_name,
            site_id: site_id,
            site_name: site_name,
            details: [],
            item_index: itemIndex // 添加索引以区分同一规则的不同项
          })
        }
      })
    }
  })
  
  return rules
})

const selectedRule = computed(() => {
  if (selectedRuleIndex.value >= 0 && selectedRuleIndex.value < rulesData.value.length) {
    return rulesData.value[selectedRuleIndex.value]
  }
  return null
})

watch(() => props.visible, (newVal) => {
  if (newVal) {
    selectedRuleIndex.value = -1
    expandedRules.value = []
    trustLoading.value = false
    // 自动选择第一个失败的规则
    const firstFailedIndex = rulesData.value.findIndex(rule => !rule.result)
    if (firstFailedIndex >= 0) {
      selectedRuleIndex.value = firstFailedIndex
    } else if (rulesData.value.length > 0) {
      selectedRuleIndex.value = 0
    }
  }
})

const formatRuleName = (key) => {
  const nameMap = {
    'temporary_facility_fee_rate': '临时设施费费率',
    'material_comparison': '材料比对',
    'field_validation': '字段验证',
    'specification_check': '规格检查'
  }
  return nameMap[key] || key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

const extractDetails = (item) => {
  const details = []
  
  // 提取字段验证详情
  if (item.field_validations) {
    Object.keys(item.field_validations).forEach(fieldKey => {
      const validation = item.field_validations[fieldKey]
      details.push({
        field_name: fieldKey,
        result: validation.result,
        expected_value: validation.expected_value,
        actual_value: validation.actual_value,
        reason: validation.reason
      })
    })
  }
  
  // 提取材料比对详情
  if (item.material_comparisons) {
    item.material_comparisons.forEach(material => {
      details.push({
        material_name: material.material_name,
        specification: material.specification,
        result: material.result,
        differences: material.differences,
        reason: material.reason
      })
    })
  }
  
  // 提取其他详情
  if (item.details && Array.isArray(item.details)) {
    details.push(...item.details)
  }
  
  return details
}

const getResultSummary = (rule) => {
  if (rule.result) {
    return rule.reason || '验证通过'
  } else {
    return rule.reason || '验证失败'
  }
}

const selectRule = (index) => {
  selectedRuleIndex.value = index
}

const getDisplayRuleName = (rule) => {
  let name = rule.rule_name
  // // 如果同一规则有多个项目，显示项目信息
  // if (rule.project_id || rule.site_id) {
  //   const projectInfo = rule.project_name || rule.project_id
  //   const siteInfo = rule.site_name || rule.site_id
  //   if (projectInfo && siteInfo) {
  //     name += `\n(${projectInfo} - ${siteInfo})`
  //   } else if (projectInfo) {
  //     name += `\n (${projectInfo})`
  //   } else if (siteInfo) {
  //     name += `\n(${siteInfo})`
  //   }
  // }
  return name
}

const handleOverlayClick = () => {
  // 点击遮罩层不关闭模态框，需要用户主动点击关闭按钮
}

// 处理信任规则
const handleTrustRule = async () => {
  if (!selectedRule.value) {
    return
  }
  
  trustLoading.value = true
  
  try {
    // 调试：输出checkData和selectedRule的结构
    console.log('checkData结构:', JSON.stringify(props.checkData, null, 2))
    console.log('selectedRule结构:', JSON.stringify(selectedRule.value, null, 2))
    
    // 获取当前选中条目的项目信息
    const misid = selectedRule.value.project_id
    
    // 尝试从多个可能的位置获取taskid
    const taskid = selectedRule.value.site_id
    
    const rule = selectedRule.value.rule_name
    
    console.log('提取的参数 - misid:', misid, 'taskid:', taskid, 'rule:', rule)
    console.log('所有可能的taskid字段:', {
      task_id: props.checkData.task_id,
      subtaskId: props.checkData.subtaskId,
      taskId: props.checkData.taskId,
      subtask_id: props.checkData.subtask_id,
      data_task_id: props.checkData.data && props.checkData.data.task_id,
      data_subtaskId: props.checkData.data && props.checkData.data.subtaskId,
      data_taskId: props.checkData.data && props.checkData.data.taskId
    })
    
    // 如果缺少必要参数，提示用户
    if (!misid || !taskid) {
      throw new Error('缺少项目信息，无法执行信任操作。misid: ' + misid + ', taskid: ' + taskid)
    }
    
    // 调用信任接口
    const response = await uni.request({
      url: './api/truth',
      method: 'POST',
      data: {
        misid: misid,
        taskid: taskid,
        rule: rule
      },
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.statusCode === 200) {
      uni.showToast({
        title: '反馈成功，重新创建项目时生效',
        icon: 'success',
        duration: 3000
      })
    } else {
      throw new Error(response.data.message || '信任失败')
    }
    
  } catch (error) {
    console.error('信任规则失败:', error)
    uni.showToast({
      title: '信任失败: ' + (error.message || '网络错误'),
      icon: 'error',
      duration: 3000
    })
  } finally {
    trustLoading.value = false
  }
}

const exportReport = () => {
  // 生成报告内容
  let reportContent = '历史自检失败报告\n'
  reportContent += '=' .repeat(50) + '\n\n'
  
  // 按规则名称分组
  const rulesByGroup = {}
  rulesData.value.forEach(rule => {
    if (!rulesByGroup[rule.rule_name]) {
      rulesByGroup[rule.rule_name] = []
    }
    rulesByGroup[rule.rule_name].push(rule)
  })
  
  let ruleIndex = 1
  Object.keys(rulesByGroup).forEach(ruleName => {
    const rules = rulesByGroup[ruleName]
    
    if (rules.length === 1) {
      // 单个规则项
      const rule = rules[0]
      reportContent += `${ruleIndex}. ${ruleName}\n`
      reportContent += `   状态: ${rule.result ? '通过' : '失败'}\n`
      
      // 添加项目和站点信息
      if (rule.project_id || rule.site_id) {
        reportContent += `   项目信息: ${rule.project_name || rule.project_id || '无'}\n`
        reportContent += `   站点信息: ${rule.site_name || rule.site_id || '无'}\n`
      }
      
      reportContent += `   详细说明: ${rule.reason || '无详细说明'}\n\n`
      ruleIndex++
    } else {
      // 多个规则项（同一规则的不同项目）
      reportContent += `${ruleIndex}. ${ruleName} (共${rules.length}个项目)\n`
      
      rules.forEach((rule, subIndex) => {
        reportContent += `   ${subIndex + 1}. 项目: ${rule.project_name || rule.project_id || '未知项目'}`
        if (rule.site_name || rule.site_id) {
          reportContent += `, 站点: ${rule.site_name || rule.site_id}`
        }
        reportContent += `\n`
        reportContent += `      状态: ${rule.result ? '通过' : '失败'}\n`
        reportContent += `      详细说明: ${rule.reason || '无详细说明'}\n\n`
      })
      
      ruleIndex++
    }
  })
  
  // 创建并下载文件
  try {
    const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `历史自检失败报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    uni.showToast({
      title: '报告导出成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('导出报告失败:', error)
    uni.showToast({
      title: '导出失败',
      icon: 'error'
    })
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
}

.modal-container {  
  background: white;
  border-radius: 8px;
  width: 95%;
  max-width: 1200px;
  height: 85vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  flex: 1;
  overflow: hidden;
}

.content-layout {
  display: flex;
  height: 100%;
}

/* 左侧规则列表 */
.rules-panel {
  width: 350px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.panel-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.expand-controls {
  display: flex;
  gap: 8px;
}

.expand-btn {
  font-size: 12px;
  color: #007bff;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #007bff;
}

.expand-btn:hover {
  background: #007bff;
  color: white;
}

.rules-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.rule-item {
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.rule-item:hover {
  border-color: #007bff;
}

.rule-item.rule-selected {
  border-color: #007bff;
  background: #f8f9fa;
}

.rule-item.rule-failed {
  border-left: 4px solid #dc3545;
}

.rule-item.rule-passed {
  border-left: 4px solid #28a745;
}

.rule-header {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rule-status {
  display: flex;
  align-items: center;
  flex: 1;
}

.status-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
}

.status-icon.success {
  background: #28a745;
  color: white;
}

.status-icon.error {
  background: #dc3545;
  color: white;
}

.rule-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.expand-icon {
  font-size: 12px;
  color: #666;
  transition: transform 0.2s;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.rule-details-preview {
  padding: 0 12px 12px;
  border-top: 1px solid #f5f5f5;
}

.detail-preview-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
  font-size: 12px;
}

.detail-preview-item.detail-failed {
  color: #dc3545;
}

.detail-status {
  width: 16px;
  margin-right: 6px;
}

.detail-name {
  flex: 1;
}

.more-details {
  font-size: 12px;
  color: #666;
  font-style: italic;
  margin-top: 4px;
}

/* 右侧详细信息 */
.details-panel {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.rule-details {
  max-width: 800px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #eee;
}

.detail-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.detail-status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
}

.detail-status-badge.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.detail-status-badge.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.rule-description {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.description-label {
  font-weight: bold;
  color: #495057;
  margin-right: 8px;
}

.description-text {
  color: #6c757d;
}

.result-summary {
  margin-bottom: 20px;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #dee2e6;
}

.summary-label {
  font-weight: bold;
  color: #495057;
  margin-right: 8px;
}

.summary-text {
  color: #6c757d;
}

.summary-text.success-text {
  color: #28a745;
}

.summary-text.error-text {
  color: #dc3545;
}

.rule-reason-section {
  margin-top: 20px;
}

.reason-content {
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #dee2e6;
  background: #f8f9fa;
}

.reason-content.success-content {
  background: #d4edda;
  border-color: #c3e6cb;
}

.reason-content.error-content {
  background: #f8d7da;
  border-color: #f5c6cb;
}

.reason-content .reason-text {
  color: #495057;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.reason-content.success-content .reason-text {
  color: #155724;
}

.reason-content.error-content .reason-text {
  color: #721c24;
}

/* 信任按钮样式 */
.trust-section {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.trust-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  background: #28a745;
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120px;
}

.trust-btn:hover:not(:disabled) {
  background: #218838;
}

.trust-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.details-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.detail-item {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
}

.detail-item.detail-failed {
  border-color: #dc3545;
  background: #fff5f5;
}

.detail-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.detail-status-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
}

.detail-status-icon.success {
  background: #28a745;
  color: white;
}

.detail-status-icon.error {
  background: #dc3545;
  color: white;
}

.detail-item-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.field-detail, .material-detail {
  margin-left: 28px;
}

.value-comparison {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.label {
  font-weight: 500;
  color: #495057;
  width: 80px;
  margin-right: 8px;
}

.expected-value {
  color: #28a745;
  font-weight: 500;
}

.actual-value {
  color: #6c757d;
}

.actual-value.error-value {
  color: #dc3545;
  font-weight: 500;
}

.error-reason, .material-reason {
  margin-top: 8px;
  padding: 8px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
}

.reason-text {
  color: #856404;
}

.material-info {
  margin-bottom: 12px;
}

.material-name {
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 4px;
}

.material-spec {
  font-size: 12px;
  color: #6c757d;
}

.differences {
  margin-top: 12px;
}

.differences-title {
  font-weight: 500;
  color: #495057;
  display: block;
  margin-bottom: 8px;
}

.difference-item {
  display: flex;
  margin-bottom: 4px;
  padding: 4px 8px;
  background: #f8d7da;
  border-radius: 4px;
}

.diff-field {
  font-weight: 500;
  color: #721c24;
  margin-right: 8px;
}

.diff-description {
  color: #721c24;
}

.general-reason {
  margin-left: 28px;
  padding: 8px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
}

.no-details, .no-selection {
  text-align: center;
  padding: 40px 20px;
  color: #6c757d;
}

.no-details-text, .no-selection-text {
  font-size: 14px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #eee;
  flex-shrink: 0;
}

.export-btn {
  padding: 8px 16px;
  border: 1px solid #007bff;
  border-radius: 4px;
  background: #007bff;
  color: white;
  cursor: pointer;
  font-size: 14px;
}

.export-btn:hover {
  background: #0056b3;
}

.close-footer-btn {
  padding: 8px 16px;
  border: 1px solid #6c757d;
  border-radius: 4px;
  background: white;
  color: #6c757d;
  cursor: pointer;
  font-size: 14px;
}

.close-footer-btn:hover {
  background: #f8f9fa;
}
</style>